<template>
	<view class="login-page">
		<!-- 黑色动态背景 -->
		<view class="bg">
			<view class="blob b1"></view>
			<view class="blob b2"></view>
			<view class="blob b3"></view>
		</view>

		<!-- 内容 -->
		<view class="container">
			<view class="panel">
				<view class="title">欢迎登录</view>
	
				<view class="tabs">
					<view :class="['tab', activeTab==='login' ? 'active' : '']" @click="activeTab='login'">登录</view>
					<view :class="['tab', activeTab==='register' ? 'active' : '']" @click="activeTab='register'">注册</view>
				</view>
	
				<view class="form">
					<!-- 已删除顶部全局错误提示 -->

					<input
						class="input"
						:class="{ 'input-error': !!usernameError }"
						type="text"
						v-model="username"
						placeholder="用户名"
						placeholder-class="ph"
					/>
					<transition name="fade-slide">
						<view class="error-inline" v-if="usernameError">
							<uni-icons type="smallcircle-filled" :size="12" color="#ff6b6b" />
							<text class="error-inline-text">{{ usernameError }}</text>
						</view>
					</transition>

					<input
						class="input"
						:class="{ 'input-error': !!passwordError }"
						type="password"
						v-model="password"
						placeholder="密码"
						placeholder-class="ph"
					/>
					<transition name="fade-slide">
						<view class="error-inline" v-if="passwordError">
							<uni-icons type="smallcircle-filled" :size="12" color="#ff6b6b" />
							<text class="error-inline-text">{{ passwordError }}</text>
						</view>
					</transition>
					<!-- 注册页专属：确认密码输入框 -->
					<view v-if="activeTab==='register'">
						<input 
							class="input"
							:class="{ 'input-error': !!passwordConfirmError }"
							type="password" 
							v-model="passwordConfirm" 
							placeholder="确认密码" 
							placeholder-class="ph" 
						/>
						<transition name="fade-slide">
							<view class="error-inline" v-if="passwordConfirmError">
								<uni-icons type="smallcircle-filled" :size="12" color="#ff6b6b" />
								<text class="error-inline-text">{{ passwordConfirmError }}</text>
							</view>
						</transition>
					</view>
	
					<button class="btn primary" :disabled="loading" @click="handleSubmit">
						{{ activeTab==='login' ? '登录' : '注册' }}
					</button>
	
					<button class="btn ghost" :disabled="loading" @click="goBack">返回</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, watch } from 'vue'
import { namePassLogin, usernamePassword } from '@/api/auth.js'
import http from '@/utils/request.js'

// ===== 状态管理 =====
const activeTab = ref('login')
const username = ref('')
const password = ref('')
const passwordConfirm = ref('')
const loading = ref(false)
const usernameError = ref('')
const passwordError = ref('')
const passwordConfirmError = ref('')
// 已移除 generalError 状态

const STORAGE_USER_KEY = 'dy_user_state'

// ===== 基础功能 =====
const goBack = () => {
	uni.navigateBack({ delta: 1 })
}

const clearErrors = () => {
	usernameError.value = ''
	passwordError.value = ''
	passwordConfirmError.value = ''
	// 已移除 generalError 清空
}

watch(activeTab, (newTab) => {
	clearErrors()
	if (newTab === 'login') {
		passwordConfirm.value = ''
	}
})

// ===== 表单验证 =====
const validateLoginForm = () => {
	let isValid = true
	
	if (!username.value.trim()) {
		usernameError.value = '用户名不能为空'
		isValid = false
	} else {
		usernameError.value = ''
	}
	
	if (!password.value.trim()) {
		passwordError.value = '密码不能为空'
		isValid = false
	} else if (password.value.length < 6) {
		passwordError.value = '密码长度不能少于6位'
		isValid = false
	} else {
		passwordError.value = ''
	}
	
	return isValid
}

const validateRegisterForm = () => {
	let isValid = true
	
	isValid = validateLoginForm()
	
	if (!passwordConfirm.value.trim()) {
		passwordConfirmError.value = '请确认密码'
		isValid = false
	} else if (passwordConfirm.value !== password.value) {
		passwordConfirmError.value = '两次输入的密码不一致'
		isValid = false
	} else {
		passwordConfirmError.value = ''
	}
	
	return isValid
}

// ===== 接口请求 =====
const handleLogin = async () => {
	try {
		const resp = await namePassLogin({ 
			username: username.value.trim(), 
			password: password.value.trim() 
		})

		if (resp.code == 400) {
			handleApiError(resp)
			return
		}

		await handleLoginSuccess(resp)
	} catch (err) {
		handleRequestError(err)
	}
}

const handleRegister = async () => {
	try {
		const registerParams = {
			username: username.value.trim(),
			password: password.value.trim()
		}

		const resp = await usernamePassword({ 
			username: username.value.trim(), 
			password: password.value.trim() 
		})

		if (resp.code == 400) {
			handleApiError(resp)
			return
		}

		uni.showToast({ title: '注册成功，请登录', icon: 'none' })
		setTimeout(() => {
			activeTab.value = 'login'
		}, 1500)
	} catch (err) {
		handleRequestError(err)
	}
}

/**
 * 处理接口返回的错误信息（仅显示字段级错误，换行展示多个错误）
 */
const handleApiError = (resp) => {
	if (Array.isArray(resp?.data)) {
		resp.data.forEach(item => {
			// 多个错误用换行符连接
			const errorText = (item.errors || []).join('\n')
			if (item.field === 'username') {
				usernameError.value = errorText
			}
			if (item.field === 'password') {
				passwordError.value = errorText
			}
			if (item.field === 'passwordConfirm') {
				passwordConfirmError.value = errorText
			}
		})
	} else {
		// 非字段级错误显示在第一个输入框下方
		const errorMsg = resp?.message || '操作失败，请稍后重试'
		usernameError.value = errorMsg
	}
}

/**
 * 处理请求异常（字段错误换行展示）
 */
const handleRequestError = (err) => {
	const errorData = err?.data
	if (Array.isArray(errorData)) {
		errorData.forEach(item => {
			const errorText = (item.errors || []).join('\n')
			if (item.field === 'username') {
				usernameError.value = errorText
			}
			if (item.field === 'password') {
				passwordError.value = errorText
			}
			if (item.field === 'passwordConfirm') {
				passwordConfirmError.value = errorText
			}
		})
	} else {
		const errorMsg = err?.message || '网络异常，请检查网络连接'
		usernameError.value = errorMsg
	}
}

const handleLoginSuccess = async (resp) => {
	const token = resp?.data;
	if (token) {
		http.setStoredToken(token)
	}

	const userPayload = resp?.data?.user || {
		nickname: username.value.trim(),
		avatar: 'https://via.placeholder.com/96/111111/FFFFFF?text=U',
		uid: String(Date.now()).slice(-7)
	}

	const userInfo = {
		isLoggedIn: true,
		nickname: userPayload.nickname || username.value.trim(),
		avatar: userPayload.avatar,
		uid: userPayload.uid
	}

	try {
		uni.setStorageSync(STORAGE_USER_KEY, userInfo)
	} catch (e) {
		console.error('存储用户信息失败：', e)
	}

	uni.$emit('loginSuccess', userInfo)
	uni.showToast({ title: '登录成功', icon: 'none' })
	
	//回到首页
	setTimeout(()=>{
		uni.reLaunch({
			url:"/pages/index/index"
		})
	},500);
}

// ===== 提交事件入口 =====
const handleSubmit = async () => {
	if (loading.value) return
	
	clearErrors()

	if (activeTab.value === 'login') {
		if (!validateLoginForm()) return
	} else {
		if (!validateRegisterForm()) return
	}

	loading.value = true
	try {
		if (activeTab.value === 'login') {
			await handleLogin()
		} else {
			await handleRegister()
		}
	} finally {
		loading.value = false
	}
}
</script>

<style scoped lang="scss">
.login-page {
	width: 100%;
	height: 100vh;
	overflow: hidden;
	background: #000;
	position: relative;
}

.bg {
	position: absolute;
	inset: 0;
	overflow: hidden;
	filter: blur(16rpx);
}

.blob {
	position: absolute;
	width: 480rpx;
	height: 480rpx;
	border-radius: 50%;
	opacity: 0.24;
	mix-blend-mode: screen;
}
.b1 { background: #7c3aed; animation: float1 9s ease-in-out infinite; left: -80rpx; top: -60rpx; }
.b2 { background: #0ea5e9; animation: float2 11s ease-in-out infinite; right: -120rpx; top: 120rpx; }
.b3 { background: #f59e0b; animation: float3 13s ease-in-out infinite; left: 120rpx; bottom: -140rpx; }

@keyframes float1 { 0%,100% { transform: translate(0,0) scale(1); } 50% { transform: translate(40rpx,20rpx) scale(1.1); } }
@keyframes float2 { 0%,100% { transform: translate(0,0) scale(1); } 50% { transform: translate(-30rpx,30rpx) scale(1.06); } }
@keyframes float3 { 0%,100% { transform: translate(0,0) scale(1); } 50% { transform: translate(30rpx,-20rpx) scale(1.08); } }

.container {
	position: relative;
	z-index: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-top: 160rpx;
	color: #fff;
}

.panel {
	width: 88%;
	max-width: 700rpx;
	background: rgba(255,255,255,0.06);
	border: 2rpx solid rgba(255,255,255,0.08);
	border-radius: 20rpx;
	backdrop-filter: blur(8rpx);
	padding: 40rpx 32rpx 32rpx;
	box-sizing: border-box;
}

.title {
	font-size: 40rpx;
	font-weight: 700;
	margin-bottom: 28rpx;
	text-align: center;
}

.tabs {
	display: flex;
	background: rgba(255,255,255,0.08);
	border-radius: 16rpx;
	padding: 6rpx;
	margin: 0 auto;
	width: 70%;
}
.tab {
	min-width: 38%;
	text-align: center;
	padding: 16rpx 24rpx;
	font-size: 28rpx;
	color: rgba(255,255,255,0.6);
}
.tab.active {
	color: #fff;
	background: rgba(255,255,255,0.14);
	border-radius: 12rpx;
}

.form {
	width: 100%;
	margin-top: 28rpx;
}

.input {
	width: 100%;
	height: 88rpx;
	padding: 0 24rpx;
	border-radius: 12rpx;
	background: rgba(255,255,255,0.12);
	color: #fff;
	font-size: 28rpx;
	margin-bottom: 24rpx;
	box-sizing: border-box;
}
.ph {
	color: rgba(255,255,255,0.5);
}

.btn {
	width: 100%;
	height: 88rpx;
	border-radius: 12rpx;
	font-size: 30rpx;
	margin-top: 10rpx;
	box-sizing: border-box;
	display: block;
}
.btn.primary {
	background: linear-gradient(135deg, #7c3aed, #0ea5e9);
	color: #fff;
}
.btn.ghost {
	background: transparent;
	color: rgba(255,255,255,0.9);
	border: 2rpx solid rgba(255,255,255,0.28);
}

.input-error {
	border: 2rpx solid #ff6b6b;
	background: rgba(255, 107, 107, 0.08);
}

.error-inline {
	display: flex;
	align-items: flex-start; /* 顶部对齐，适配多行文本 */
	gap: 8rpx;
	margin: 6rpx 0 18rpx 6rpx;
}
.error-inline-text {
	color: #ff8a8a;
	font-size: 24rpx;
	white-space: pre-line; /* 启用换行符换行 */
	line-height: 1.5; /* 多行时增加行高，提升可读性 */
}

.fade-enter-active, .fade-leave-active {
	transition: opacity .2s ease;
}
.fade-enter-from, .fade-leave-to { opacity: 0; }

.fade-slide-enter-active, .fade-slide-leave-active {
	transition: all .2s ease;
}
.fade-slide-enter-from, .fade-slide-leave-to {
	opacity: 0;
	transform: translateY(-6rpx);
}
</style>